// 去重
export function unique(array: any[]): any[] {
  return Array.from(new Set(array))
}

/**
 * 使用 mapFn 映射后的值去重
 * @param array
 * @param mapFn
 *
 * uniqueBy([2.1, 1.2, 2.3], Math.floor);
 * // => [2.1, 1.2]
 *
 * uniqueBy([{ 'a': 1 }, { 'a': 2 }, { 'a': 1 }], x => x.a);
 * // => [{ 'a': 1 }, { 'a': 2 }]
 */
export function uniqueBy(array: any[], mapFn: (element: any) => any): any[] {
  if (array == null || !array.length) return []
  const result = []
  const arrayMap = array.map(mapFn)
  const set = new Set()
  for (let i = 0; i < array.length; i++) {
    const element = arrayMap[i]
    if (!set.has(element)) {
      set.add(element)
      result.push(array[i])
    }
  }
  return result
}

/**
 * 使用 isEqual 做比较函数去重
 * @param array
 * @param isEqual
 *
 * const array = [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 1 }, { 'a': 1, 'b': 2 }];
 *
 * uniqueWith(array, (x,y) => x.a == y.a && x.b == y.b);
 * // => [{ 'a': 1, 'b': 2 }, { 'a': 2, 'b': 1 }]
 */
export function uniqueWith(array: any[], isEqual: (x: any, y: any) => boolean): any[] {
  if (array == null || !array.length) return []
  const result = [array[0]]
  for (let i = 1; i < array.length; i++) {
    const newVal = array[i]
    let found = false
    // 检查从[0, i-1]区间的元素，是否有和第i个元素匹配的
    for (let j = 0; j < i; j++) {
      if (isEqual(newVal, array[j])) {
        found = true
        break
      }
    }
    if (!found) result.push(newVal)
  }
  return result
}


